package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserSService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service("iUserSService")

public class UserServiceImpl implements IUserSService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String passWord) {


        int resultCount = userMapper.checkUserName(username);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        // 密码md5登陆
//        String md5Password = MD5Util.MD5EncodeUtf8(passWord);
        User user = userMapper.selectLogin(username, passWord);
        if (user == null) {
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登陆成功", user);
    }

    public ServerResponse<String> register(User user) {

        ServerResponse response = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!response.isSuccess()) {
            return response;
        }

        response = this.checkValid(user.getPassword(), Const.PASSWORD);
        if (!response.isSuccess()) {
            return response;
        }
        user.setRole(Const.Role.ROLE_CUSTOM);
        //md5加密密码数据库中用户的密码不应该是明文的
//        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        user.setPassword(user.getPassword());
        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    public ServerResponse<String> checkValid(String str, String type) {

        if (StringUtils.isNotBlank(str)) {
            if (Const.USERNAME.equals(type)) {
                int resultCount = userMapper.checkUserName(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if (Const.PASSWORD.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    public ServerResponse<String> selectQuestion(String username) {

        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if (response.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (question != null && StringUtils.isNotBlank(question)) {
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    public ServerResponse<String> checkAnswer(String username, String question, String answer) {

        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0) {

            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PRIFIX + username, forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }

    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {

        if (StringUtils.isBlank(forgetToken)) {
            return ServerResponse.createByErrorMessage("token 需要传递");
        }
        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if (response.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getValue(TokenCache.TOKEN_PRIFIX + username);
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("token无效或已过期");
        }
        if (StringUtils.equals(token, forgetToken)) {
            int resultCount = userMapper.updatePasswordByUsername(username, passwordNew);
            if (resultCount > 0) {
                return ServerResponse.createBySuccessMessage("更新密码成功");
            }
        } else {
            return ServerResponse.createByErrorMessage("token 错误请重新获取");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    public ServerResponse<String> resetPassword(String password, String passwordNew, User user) {
        //防止横向越权,在更新密码的同时一定要验证这个密码是这个用户的
        int resultCount = userMapper.checkPassword(password, user.getId());
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("就密码错误");
        }
        user.setPassword(passwordNew);
        resultCount = userMapper.updateByPrimaryKeySelective(user);
        if (resultCount > 0) {
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    public ServerResponse<User> updataInformation(User user) {

        int resuletCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (resuletCount > 0) {
            return ServerResponse.createByErrorMessage("邮箱已存在,请更换邮箱在尝试更新");
        }
        User updataUser = new User();
        updataUser.setId(user.getId());
        updataUser.setEmail(user.getEmail());
        updataUser.setPhone(user.getPhone());
        updataUser.setQueastion(user.getQueastion());
        updataUser.setAnswer(user.getAnswer());

        resuletCount = userMapper.updateByPrimaryKeySelective(updataUser);
        if (resuletCount > 0) {
            return ServerResponse.createBySuccess("更新用户信息成功,", updataUser);
        }

        return ServerResponse.createByErrorMessage("更新用户信息失败");
    }

    public ServerResponse<User> getInformation(Integer userId) {

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    //backend

    /**
     * 校验是否是管理员
     * @param user
     * @return
     */
    public ServerResponse checkAdminRole(User user){

        if (user!=null&&user.getRole().intValue()==Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }

        return ServerResponse.createByError();
    }

}
